#include "app_rs485.h"
#include "app_sub_can.h"

#include "bsp_gpio.h"
#include "bsp_usart.h"
#include "bsp.h"
#include "main.h"


static osTimeCost_T pTimecost[3] = {0};
RS485_t rs485;

void app_485_state_init(void)
{
    rs485.test_en = false;

    subCan.txMes1.mes.txST485 = 0;
    subCan.txMes1.mes.rxST485 = 0; 

    for (uint8_t i = 0; i < 100; i++)
    {
        rs485.tx_buffer[i] = i;
    }

    for (uint8_t i = 0; i < 100; i++)
    {
        rs485.rx_buffer[i] = 0;
    }        
}

void app_485_run(void)
{
    static uint16_t cnt = 0;
    static uint8_t  step = 0;
    
    switch (step)
    {
        case 0:
        if(rs485.test_en == true)
        {
            rs485.test_en = false;
            app_485_state_init();
            dv_DIDO.fwrite(IO_USART_RX_EN,false);    
            step = 1;              
        }        
        break;

        case 1:        
        cnt++;
        if(cnt>=SYS_HEART_MS(100))
        {
            cnt = 0;
            osTaskGetTimeCost(&pTimecost[0]);
            dv_UART.fwrite_data(rs485.tx_buffer,100);
            osTaskGetTimeCost(&pTimecost[0]);
            subCan.txMes1.mes.txST485 = 1;            
            step = 2; 
        }            
        break;

        case 2:
        cnt++;
        if(cnt >= SYS_HEART_MS(50))
        {   
            cnt = 0;
            step = 3;
            dv_DIDO.fwrite(IO_USART_RX_EN,true);
        }        
        break;

        case 3:
        if(dv_UART.u8UartRecvCnt >= 100)
        {
            dv_UART.fread_data(rs485.rx_buffer,1);
			subCan.txMes1.mes.rxST485 = 1;
            for (uint8_t i = 0; i < 100; i++)
            {
                if(rs485.rx_buffer[i]!= rs485.tx_buffer[i])
                {
                    subCan.txMes1.mes.rxST485 = 0;
                    break;
                }
            }			
        }
        if(subCan.txMes1.mes.rxST485 == 0)
        {
            cnt++;
            if(cnt >= SYS_HEART_MS(1000))
            {
                cnt = 0;
                step = 0;
            }
        }
        else
        {
            step = 0;
        }
        
        dv_DIDO.LEDCtrl.State = 0;
        break;
        default:
        break;
    }
}